import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import React, { useState } from 'react';
import Cloud from 'leancloud-storage'

const getBase64 = (img, callback) => { //将图片资源对象转换为base64编码
  const reader = new FileReader();  //MDN
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = (file) => {  //上传前的拦截约束
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }

  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }

  return isJpgOrPng && isLt2M;
};

const ImgUpload = (props) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  console.log('ImgUpload组件',props);
  const handleCustom = (info)=>{ //自定义上传函数
    // console.log(info);  //即将上传的图片资源对象
    setLoading(true)
    getBase64(info.file,(base64)=>{
      let file = new Cloud.File('article.png',{base64})  //构建LeanCloud资源对象
      file.save().then(res=>{  //向LeanCloud云端提交资源
        // console.log(res);
        let {url} = res.attributes  //后端下发的在线图片路径
        setLoading(false)
        setImageUrl(url)
        props.onChange(url)  //让表单组件获取到url
      })
      // console.log(base64);
    })
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      customRequest={handleCustom}
      beforeUpload={beforeUpload}
    >
      {imageUrl||props.fileList ? (
        <img
          src={imageUrl||props.fileList}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};

export default ImgUpload;